// ----------------------------------------------------全局变量区-----------
var endFlag = false;
var readArticleCount = 0;
var needReadArticleNum = 45;
var appPackageName = "com.app.kankan";
// var nowAppPackageName = "com.app.yunli";
// var nowAppPackageName = "com.app.qitian";

// var nowAppPackageName = "com.app.quanmin";


var storage = null;
// ----------------------------------------------------方法区-----------------------

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

/**
 * 
 * 通过bounds 点击
 * @param {*} btn  按钮对象
 */
function clickBtnByBoundsCenter(btn) {
    var position = btn.bounds();
    Tap(position.centerX(), position.centerY());
    sleep(1000);
}

/**
 * 判断是否主页
 */
function ifMainPage() {
    var flagBtn = desc("新手任务").findOne(3000);
    if (flagBtn) {
        return true;
    }
    return false;
}

/**
 * 判断是否阅读页面
 */
function ifReadPage() {
    var flagBtn = desc("推荐").findOne(3000);
    if (flagBtn) {
        return true;
    }
    return false;
}

/**
 * 是否登录
 */
function ifLogined() {
    sleep(2000);
    var userInfoBtn = desc("个人中心").depth(11).findOne(1000);
    sleep(2000);

    // toastLog(.bounds());
    if (userInfoBtn == null) {
        toastLog("未找到个人中心按钮");
        // return false;
    } else {
        sleep(1000);
        // 切换到个人中心
        clickBtnByBoundsCenter(userInfoBtn);
        sleep(1000);
        clickBtnByBoundsCenter(userInfoBtn);
        sleep(1000);

    }
    // 如果找不到今日收入，则未登录
    // var loginBtn = desc("登录").findOne(2000);
    var income = desc("今日收入").findOne(2000);
    if (!income) {
        // toastLog("未登录");
        return false;
    } else {
        toastLog("已登录");
    }
    return true;
}

/**
 * 模拟下拉
 */
function simulateScorllDown() {
    // toastLog("下拉")
    sleep(2000);

    // var starx = random(500, 600);
    // var starty = device.height-100;
    // Swipe(starx, starty, starx , starty /2, random(400, 500));


    var starx = random(500, 600);
    var starty = random(600, 700);
    Swipe(starx, starty, starx, starty - 500, random(1000, 2000));
    sleep(1000);
}


/**
 * 进入文章,需要修复
 */
function clickAnArticle() {
    // 文章列表
    var first = className("android.view.View").findOne(3000);
    if (first) {
        // toastLog("找到了");
        // clickBtnByBounds(first);
        sleep(2000);
        toastLog("点击文章");

        // 如果不在可视范围，则点击下一篇
        var clickY = first.bounds().centerY();
        if (first.bounds().centerY() < 100) {
            clickY = 300;
        }
        toastLog("Y轴" + clickY);
        Tap(100, clickY);
        sleep(2000);
    } else {
        // 这里有问题呀
        toastLog("未找到文章列表");
    }
}

/**
 * 完成一篇文章
 */
function finishReadAnArticle(readArticleCount) {
    sleep(1000);
    var ifFinished = false;
    var ifArticleDetailPage = true;
    // 先判断是否在文章页面中
    var detailBtn = desc("任务详情").findOne(4000);
    if (!detailBtn) {
        toastLog("不在文章页");
        // 广告页，需要返回
        if (checkIfAdPage()) {
            back();
        }
        sleep(2000);
        if (!ifReadPage()) {
            switchToReadTabBar();
        }
        ifArticleDetailPage = false;
        return false;
    }
    var startTime = new Date();
    // todo 判断是否在广告页中
    while (!ifFinished) {

        // 超过三分钟就算成功吧- -
        if (new Date() - startTime > 1000 * 60 * 3) {
            toastLog("超时退出文章" + readArticleCount);
            return true;
        }
        sleep(4000);

        // 判断文章是否已经拉到底部
        var finishBtn = descStartsWith("阅读完成").findOne(2000);

        if (finishBtn == null) {
            toastLog("未找到阅读完成按钮");
            if (checkIfAdPage()) {
                back();
            }
            return false;
        }

        // 判断阅读完成 是否可见 

        var ifNotVisible = !checkIfVisibleArticleItem(finishBtn.bounds())
        if (ifNotVisible) {
            toastLog("文章未到底，已阅读文章" + readArticleCount);
            log(finishBtn.bounds());
            simulateScorllDown();
        } else {
            // 判断阅读完成倒计时是否结束
            // var realFinishBtn = desc("阅读完成").findOne(2000);
            toastLog("阅读完成" + readArticleCount);
            // 判断是否已获得奖励
            while (!checkGetAward()) {
                // 超过三分钟就算成功吧- -
                if (new Date() - startTime > 1000 * 60 * 3) {
                    toastLog("超时退出文章" + readArticleCount);
                    return true;
                }

                var realFinishBtn = desc("阅读完成").findOne(4000);
                if (realFinishBtn) {
                    // 点击阅读完成两次
                    clickBtnByBoundsCenter(realFinishBtn);
                    sleep(1000);
                    clickBtnByBoundsCenter(realFinishBtn);
                    sleep(1000);
                }
                else {
                    toast("阅读倒计时未结束，当前" + readArticleCount);
                }

            }
            // 获得奖励了
            ifFinished = true;
            toastLog("获得奖励，当前" + readArticleCount);
            return true;
            // back();

        }
    }
    return;
}
function switchToReadTabBar() {
    if (ifReadPage()) {
        return true;
    }
    if (checkIfAdPage()) {
        back();
        return false;
    }
    var readPageBtn = desc("阅读").findOne(1000);
    if (!readPageBtn) {
        toastLog("未找到阅读tabBar");
    }
    clickBtnByBoundsCenter(readPageBtn);
    sleep(1000);
    return false;
}
/**
 * 判断本次阅读是否已获得奖励
 */
function checkGetAward() {
    sleep(1000);
    var realFinishBtn = desc("已获得金币").findOne(4000);
    return realFinishBtn != null;
    // toastLog("获得阅读奖励，返回");

}

function backToReadTabBar() {
    if (!ifReadPage()) {
        switchToReadTabBar();
    }

    back();
    sleep(2000);
    if (!ifReadPage()) {
        switchToReadTabBar();
    }
}



/**
 * 将文章标题加入已阅读 列表
 */
function markReaded(title) {
    storage.put(title, "");
}
// function addReadArticleCount(){
    
// }
// function getReadArticleCount(){
    
// }

// function setReadArticleCount(){
    
// }
/**
 * 初始化存储
 */
function initStorage() {
    var storageName = new Date().Format("yyyy-MM-dd") + appPackageName;
    storage = storages.create(storageName);

    if (storage == null) {
        toastLog("初始化本地存储失败");
        return false;
    }
    // toastLog("初始化本地存储成功");

}

/**
 * 判断文章今天是否阅读过
 * @param {文章标题} title 
 */
function checkIfReadedTody(title) {
    return storage.contains(title)
}
/**
 * 判断是否在广告页面
 */
function checkIfAdPage() {
    var adTitle = id(appPackageName + ':id/title').findOne(3000);
    if (adTitle != null) {
        return true;
    }
    return false;
}
// todo 邮箱发送
function sendEmail(appName) {
    var url = "http://47.106.164.121:8080/mail/1?appName=" + appName + "&username=1111";
    http.get(url, {}, function (res, err) {
        if (err) {
            console.error(err);
            return false;
        }
        log("code = " + res.statusCode);
        log("html = " + res.body.string());
        if (res.body.string() == "true") {
            return true;
        }

    });
}
function checkIfVisibleArticleItem(rect) {
    log(rect);

    // 高一定是比宽大的
    var realHeight = device.height;
    var realWidth = device.width;

    if (realHeight < realWidth) {
        realHeight = device.width;
        realWidth = device.height;
    }

    if (rect.left > realWidth || rect.centerX < 0) {
        return false;
    }

    if (rect.bottom > realHeight || rect.bottom < 0) {
        return false;
    }

    // 顶部要比栏目高
    if (rect.top < 150) {
        return false;
    }
    return true;
}

/**
 * 退出app
 */
function exitAppByPackageName() {
    var result = shell("am force-stop " + appPackageName, true);
    sleep(500);
    return result.code == 0;
}
function main(ifRestart) {
    var rootAutomator = new RootAutomator();
    //声明模式
    auto.waitFor();
    initStorage();
    // 启动app
    launch(appPackageName);

    sleep(8000)
    // 查看是否已登录账号
    // if (!ifLogined()) {
    //     toastLog("未登录，请先登录账号")
    // }
    // 切换到阅读tabbar
    switchToReadTabBar();
    var errCount=0;
    while (readArticleCount < needReadArticleNum) {
        // 如果重启，先下拉相应次数
        if(ifRestart==true){
            for (let index = 0; index < readArticleCount; index++) {
                simulateScorllDown();  
            }
            ifRestart = false;
        }
        simulateScorllDown();
        clickAnArticle();
        if (finishReadAnArticle(readArticleCount)) {
            // backToReadTabBar();
            back();
            readArticleCount += 1;
            errCount=0;
        }else{
            errCount++;
            // 如果错误次数上限，重启app
            if(errCount>5){
                exitAppByPackageName();
                
                main(true);
            }
        }
        toastLog("已阅读文章" + readArticleCount);
    }
    // 结束一个app了
    sendEmail(appPackageName);
    
}


var array =new Array();
// array.push("com.app.quanmin")

// array.push("com.app.kankan");
// array.push("com.app.qitian");
array.push("com.app.yunli");


// while(true){
    for (var item in array){
        log(array[item])
        // 开始下一轮
        appPackageName=array[item];
        readArticleCount=0;
        main()
    }
// }

